package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.RecordCourse;
import com.xmy.cultivate.entity.excelEntity.RecordCourseExcel;
import com.xmy.cultivate.service.IRecordCourseService;
import com.xmy.cultivate.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/surveyResult")
@Scope("prototype")
public class SurveyResultController extends BaseController {
    @Autowired
    IRecordCourseService iRecordCourseService;

    @GetMapping()
    public Result surveyResultList(@RequestParam Map<String,String> reMap) {
        IPage<RecordCourse> iPage = getData(reMap);
        return new Result(Code.OK,new PageResult<>(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    private IPage<RecordCourse> getData(Map<String,String> reMap) {
        int pageNum = StringUtils.isBlank(reMap.get("pageNum")) ? 1 : Integer.parseInt(reMap.get("pageNum"));
        int pageSize = StringUtils.isBlank(reMap.get("pageSize")) ? 10 : Integer.parseInt(reMap.get("pageSize"));

        IPage<RecordCourse> iPage = new Page<>(pageNum,pageSize);

        String school_id = reMap.get("schoolId");
        String teacherId = reMap.get("teacherId");

        String status = reMap.get("status");
        String subjectsId = reMap.get("subjectsId");

        String topicId1 = reMap.get("topicId1");
        String topicId2 = reMap.get("topicId2");

        String yearPart = reMap.get("yearPart");
        String quarter = reMap.get("quarter");

        String yearClassId = reMap.get("yearClassId");
        String gradeId = reMap.get("gradeId");

        String studentName = reMap.get("studentName");
        String studentId = reMap.get("studentId");

        String lessonNum = reMap.get("lessonNum");
        String lessonType = reMap.get("lessonType");

        QueryWrapper<RecordCourse > queryWrapper =  new QueryWrapper<>();
        String field = "*," +
                "(SELECT GROUP_CONCAT(CONCAT(IF(id = 1801060218432389120,'1.','2.'),t_name,'-',o_name) SEPARATOR '    ') FROM(" +
                "SELECT t.id,t.`name` AS t_name, o.`name` AS o_name FROM survey_result AS r " +
                "INNER JOIN survey_topic AS t ON t.id = r.topic_id " +
                "INNER JOIN survey_topic_options AS o ON o.topic_id = t.id AND o.id = r.topic_options_id " +
                "WHERE r.target_id = record_course.id " +
                "GROUP BY r.topic_id" +
                ") AS s) AS surveyResultName";
        queryWrapper.select(field);
        if(StringUtils.isNotBlank(school_id)){
            queryWrapper.eq(StringUtils.isNotBlank(school_id),"school_id",school_id);
        }else{
            queryWrapper.in("school_id",this.baseSchoolIdList);
        }
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId),"teacher_id",teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType),"lesson_type",lessonType);

        queryWrapper.eq(StringUtils.isNotBlank(yearPart),"year_part",yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarter),"quarter",quarter);

        queryWrapper.eq(StringUtils.isNotBlank(yearClassId),"year_class_id",yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId),"grade_id",gradeId);

        queryWrapper.like(StringUtils.isNotBlank(studentName),"student_name",studentName);
        queryWrapper.like(StringUtils.isNotBlank(studentId),"student_id",studentId);

        queryWrapper.like(StringUtils.isNotBlank(lessonNum),"lesson_num",lessonNum);

        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("status",status);
        }
        queryWrapper.eq("deleted",0);
        if (this.sourseLeve.equals(2)){
            queryWrapper.eq("teacher_id",this.adminId);
        }

        String sql = "SELECT target_id FROM survey_result  ";
        if ((topicId1 != null && !topicId1.isEmpty()) || (topicId2 != null && !topicId2.isEmpty()))  {
            String topicSql = Objects.equals(topicId1, "1") ? "1801060356756340736" : "1801060484837801984";
            String topic2Sql = Objects.equals(topicId2, "1") ? "1801060675011739648" : "1801060717751697408";
            if (topicId1 != null && !topicId1.isEmpty() && topicId2 != null && !topicId2.isEmpty()) {
                sql += " WHERE topic_id IN (1801060218432389120,1801060276452196352) AND topic_options_id IN (" + topicSql + "," + topic2Sql + ") GROUP BY target_id HAVING COUNT(id) > 1";
            } else if (topicId1 != null && !topicId1.isEmpty()) {
                sql += " WHERE topic_id = 1801060218432389120 AND topic_options_id = " + topicSql;
            } else {
                sql += " WHERE topic_id = 1801060276452196352 AND topic_options_id = " + topic2Sql;
            }
        }
        queryWrapper.inSql("id",sql);

        iRecordCourseService.page(iPage, queryWrapper);
        return iPage;
    }

    @GetMapping("getExcelList")
    public Result getExcelList(@RequestParam Map<String, String> reMap,
                                    HttpServletResponse response) {
        String[] quarterArray = {"","寒假班","春季班","暑假班","秋季班"};
        IPage<RecordCourse> iPage = getData(reMap);
        ArrayList<RecordCourseExcel> recordCourseExcelArrayList = new ArrayList<>();
        for (RecordCourse recordCourse : iPage.getRecords()) {
            RecordCourseExcel recordCourseExcel = new RecordCourseExcel();
            BeanUtils.copyProperties(recordCourse,recordCourseExcel);
            recordCourseExcel.setYearClassSrc(ConfigData.getYearClassForNum(recordCourse.getYearClassId()));
            recordCourseExcel.setQuarterStr(quarterArray[recordCourse.getQuarter()]);
            recordCourseExcelArrayList.add(recordCourseExcel);
        }
        ExcelExportHandleUtil.export(response, "课后满意度", recordCourseExcelArrayList, RecordCourseExcel.class);
        return new Result(Code.OK, null, "导出成功");
    }

}
